/**
 * Copyright (c) 2014 zhenrongbao.com, Inc. All Rights Reserved
 * @author: jiangshuguang
 * @Date  : 14-12-5
 * @Time  : 下午6:34
 * @brief :
 */
(function () {
    var Dialog = require('common:widget/ui/dialog/dialog.js').Dialog,
        check = require('user:widget/ui/check/check.js').check,
        $page = $('.page-buydemandnewuser'),
        dialog = new Dialog(),
        data = P.data('data');

    $page.find('.use_coupon').bind('click', function () {
        calculateAmount();
        $('.coupon_info').show();
    });

    calculateAmount = function () {
        var buyAmount = $page.find('.money-input .amount').val();
        var couponAmount = 0;
        if ($('.use_coupon').attr('checked') == 'checked') {
            $('.use_coupon').attr('data') ? couponAmount = $('.use_coupon').attr('data') : couponAmount = 0;
            P.data('coupon_type',1);
        }
        var buyValue = (parseFloat(buyAmount) * 1000 - parseFloat(couponAmount) * 1000) / 1000;
        if(buyValue < 0) {
            buyValue = 0;
        }
        $('.buy_confirm .value').text('￥' + buyValue);
        P.data('buyValue',buyValue);
    };
    $page.find('.money-input').on('input keyup',function () {
        calculateAmount();
        $('.buy_confirm').addClass('active');
    });

    $page.find('.btn-buy').click(function(){
        if($(this).hasClass('btn-main')){
            var originalAmount = $.trim($page.find('.amount').val()),
                amount = P.data('buyValue');

            if(!check.amount(originalAmount)){
                return;
            }

            if(parseFloat(originalAmount)> 1000-(parseInt(data['preemption']))){
                dialog.show('您的购买金额大于1000元');
                return;
            }

            if(parseFloat(amount)> data['amount']){
                dialog.show('您的实际支付金额大于您的账户可用余额');
                return;
            }

            $(this).addClass('btn-disable').removeClass('btn-main');
            $.post('/user/purchasingpreemption',{
                amount:originalAmount,
                pid:201,
                coupon_type: P.data('coupon_type')
            },function(ret,status){
                if(ret.error_no == 0){
                    location.href="/user/buyingdemand?pid=1&trade_id="+ret.data
                }else{
                    dialog.show('系统出错，请稍后重试!');
                }
            },'json');
        }
    });
})();